﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Core.UnitOfWork;
using System.Data.Entity.Infrastructure;
using System.Data.EntityClient;
using System.Data.Common;
using System.Data.SqlClient;
using Core.Common;

namespace Core.Repository
{
    public class DataRepository : IDataRepository
    {
        public DataRepository(IUnitOfWork unitOfWork)
        {
            this.UnitOfWork = unitOfWork;
        }

        private IUnitOfWork unitOfWork;
        public IUnitOfWork UnitOfWork
        {
            get
            {
                return this.unitOfWork;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException();
                this.unitOfWork = value;
            }
        }

        public DataTable GetDataTable(string sql)
        {
            var conn = ((IObjectContextAdapter)unitOfWork.Context).ObjectContext.Connection as EntityConnection;
            var factory = DataProvider.CreateProviderFactory(conn.ConnectionString);
            DbDataAdapter da = factory.CreateDataAdapter();
            da.SelectCommand = factory.CreateCommand();
            da.SelectCommand.Connection = factory.CreateConnection();
            da.SelectCommand.Connection.ConnectionString = conn.StoreConnection.ConnectionString;
            da.SelectCommand.CommandText = sql;

            DataTable table = new DataTable();
            da.Fill(table);
            return table;
        }

        public DataSet GetDataSet(string sql)
        {
            var conn = ((IObjectContextAdapter)unitOfWork.Context).ObjectContext.Connection as EntityConnection;
            var factory = DataProvider.CreateProviderFactory(conn.ConnectionString);
            DbDataAdapter da = factory.CreateDataAdapter();
            da.SelectCommand = factory.CreateCommand();
            da.SelectCommand.Connection = factory.CreateConnection();
            da.SelectCommand.Connection.ConnectionString = conn.StoreConnection.ConnectionString;
            da.SelectCommand.CommandText = sql;

            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
    }
}
